package org.jetnuke.modules.your_account;

import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.ControllerUtils;
import net.jforum.JForumExecutionContext;
import net.jforum.SessionFacade;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.UserDAO;
import net.jforum.dao.UserSessionDAO;
import net.jforum.entities.User;
import net.jforum.entities.UserSession;
import net.jforum.repository.SecurityRepository;
import net.jforum.util.I18n;
import net.jforum.util.MD5;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.util.JetUtil;

public class Login implements IAction {
	String name, password;

	String template;
	String isadmin;
	public void setIsadmin(String isadmin) {
		this.isadmin = isadmin;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {

		
		
		UserDAO um = net.jforum.dao.DataAccessDriver.getInstance().newUserDAO();
		User user = null;
		if(name.length()>0 && password.length()>0)
			user=um.validateLogin(name, password);
		if(user==null){
			template = "not_found.vm";
				return new ActionForward(info, template);
		}
		if (user != null) {
			

			SessionFacade.setAttribute("logged", "1");
			
			UserSession tmpUs = null;
			String sessionId = SessionFacade.isUserInSession(user.getId());
			
			UserSession userSession = new UserSession(SessionFacade.getUserSession());
			
			// Remove the "guest" session
			SessionFacade.remove(userSession.getSessionId());
			
			userSession.dataToUser(user);
			
			UserSession currentUs = SessionFacade.getUserSession(sessionId);

			// Check if the user is returning to the system
			// before its last session has expired ( hypothesis )
			if (sessionId != null && currentUs != null) {
				// Write its old session data
				SessionFacade.storeSessionData(sessionId, JForumExecutionContext.getConnection());
				tmpUs = new UserSession(currentUs);
				SessionFacade.remove(sessionId);
			}
			else {
				UserSessionDAO sm = DataAccessDriver.getInstance().newUserSessionDAO();
				tmpUs = sm.selectById(userSession, JForumExecutionContext.getConnection());
			}

			I18n.load(user.getLang());

			// Autologin
			if (request.getParameter("autologin") != null
					&& SystemGlobals.getBoolValue(ConfigKeys.AUTO_LOGIN_ENABLED)) {
				userSession.setAutoLogin(true);
				ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN), "1");
				ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_USER_HASH), 
						MD5.crypt(SystemGlobals.getValue(ConfigKeys.USER_HASH_SEQUENCE) + user.getId()));
			}
			else {
				// Remove cookies for safety
				ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_USER_HASH), null);
				ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN), null);
			}
			
			if (tmpUs == null) {
				userSession.setLastVisit(new Date(System.currentTimeMillis()));
			}
			else {
				// Update last visit and session start time
				userSession.setLastVisit(new Date(tmpUs.getStartTime().getTime() + tmpUs.getSessionTime()));
			}
			
			SessionFacade.add(userSession);
			
			SessionFacade.setAttribute(ConfigKeys.TOPICS_TRACKING, new HashMap());

			ControllerUtils.addCookie(SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_DATA), 
					Integer.toString(user.getId()));

			SecurityRepository.load(user.getId(), true);
			
			//validInfo = true;
		}
		if(isadmin==null)
			JetUtil.redirect(vc,response,request.getContextPath()+"/do/your_account/home");
		else
			JetUtil.redirect(vc,response,request.getContextPath()+"/do/admin");
		return null;
	}

}
